import React, {useEffect, useState} from "react";
import {Button, PageHeader, Table, Upload, message, Card} from "antd";
import _ from "lodash";
import {ArrowLeftOutlined, LoadingOutlined, UploadOutlined} from "@ant-design/icons";
import cs from "classnames";
import {get} from "server"
import {HOST} from "project-config";
import {downloadSync} from "../../shared/libs/download";
import "./commission.less"
import VerticalAlignBottomOutlined from "@ant-design/icons/lib/icons/VerticalAlignBottomOutlined";


const headerR1 = {
	a: {
		text: "综合折扣",
		rowspan: 2
	},
	b: "最低(不含)",
}

const headerR2 = {
	a: {
		text: "综合折扣",
		rowspan: 0
	},
	b: "最高(包含)",
}

const headerR3 = {
	"a": {
		text: "客单金额",
		colspan: 2
	},
	"b": {
		rowspan: 0
	}
}

const format = (data) => {
	if (!data || data.length === 0) return [];
	const [r1, r2, ...other] = data
	const otherTmp = other.map((item, index) => ({...item, uid: index + 3}))
	return [{
		...headerR1,
		...r1,
		uid: 0,
	}, {
		...headerR2,
		...r2,
		uid: 1,
	}, {
		...headerR3,
		uid: 2,
	}, ...otherTmp]
}


const Commission = (props) => {

	const [data, setData] = useState(null);
	const [loading, setLoading] = useState(false);
	const [brandList, setBrandList] = useState([]);
	const [currentTabKey, setCurrentTabKey] = useState(1);

	const loadData = (currentTabKey) => {
		get(`/management/commission/table/readOnly/${currentTabKey}`).then(data => {
			setData(data);
		})
	}

	useEffect(() => {
		loadData(currentTabKey || 1);
		get("/management/brand/list").then(response => {
			setBrandList(response || [])
			setCurrentTabKey(response && response[0].id || "")
		})
	}, [])

	const columns = data && data.columns && data.columns.map(c => ({
		title: c,
		key: c,
		dataIndex: c,
		className: c === 'a' || c === 'b' ? 'amount-column' : 'commission-column',
		width: '100px',
		render: (v, record, index) => {
			if (index >= 3) {
				if (c === "a") {
					let min = _.get(record, "a", null);
					let max = _.get(record, "b", null);
					let cellValue = "";
					if (null == min && null == max) {
						cellValue = "";
					} else if (null == min) {
						cellValue = "<" + max;
					} else if (null == max) {
						cellValue = ">" + min;
					} else {
						cellValue = min + "-" + max;
					}
					return {
						children: <span className={'customer-order-amount'}>{cellValue}</span>,
						props: {
							colSpan: 2,
						},
					}
				}
				if (c === "b") {
					return {
						children: v,
						props: {
							colSpan: 0,
						},
					}
				}
			}
			if (v && v.colspan !== undefined) {
				return ({
					children: <span className={'customer-order-amount'}>{v.text}</span>,
					props: {
						colSpan: v.colspan,
					},
				})
			} else if (v && v.rowspan !== undefined) {
				return ({
					children: <span className={'order-discount'}>{v.text}</span>,
					props: {
						rowSpan: v.rowspan,
					},
				})
			}
			return ({
				children: index >= 3 ? v : <span className={'order-discount'}>{v}</span>,
				props: {},
			})
		}
	}))

	const rowClass = (r, i) => {
		if (i < 2) {
			return 'discount-header';
		}
	}

	const onFileChange = ({file}) => {
		const {response} = file;
		setLoading(true);
		if (!response) {
			setLoading(true);
			return;
		}
		message.success("导入成功")
		setLoading(false);
		loadData(currentTabKey);
	}


	const tabList = brandList && brandList.map(item => ({key: item.id, tab: item.name,})) || [];
	const operations = (
		<div style={{display: "flex", justifyContent: "flex-end"}}>
			<Upload
				accept=".xls,.xlsx"
				name='file'
				action={`${HOST}/management/commission/import/${currentTabKey}`}
				multiple={false}
				withCredentials={true}
				showUploadList={false}
				onChange={onFileChange}
			>
				<Button type="primary" danger>{loading ? <LoadingOutlined/> : <UploadOutlined/>}导入提成率</Button>
			</Upload>
			<Button
				style={{marginLeft: 10}}
				type="primary"
				onClick={() => downloadSync(`${HOST}/management/commission/export/${currentTabKey}`,"提成率.xls")}
			>
				<VerticalAlignBottomOutlined/>导出
			</Button>
		</div>
	)

	return <div className={'zr-panel'}>
		<div className={'zr-panel-header'}>
			<PageHeader backIcon={<ArrowLeftOutlined/>} onBack={() => window.history.back()} title='业务员提成率' subTitle=''/>
		</div>
		<Card style={{margin: "0 20px"}}
		      tabBarExtraContent={operations}
		      tabList={tabList}
		      onTabChange={key => {
			      setCurrentTabKey(key);
			      loadData(key);
		      }}
		>
			<div className={'commission-page'}>

				<Table
					bordered
					rowClassName={rowClass}
					pagination={false}
					showHeader={false}
					columns={columns}
					rowKey="uid"
					dataSource={format(data && data.data) || []}
				/>
			</div>
		</Card>

	</div>
}

export default Commission
